import requests
from tooles.ali.alisdk import getToken

class Reader:
  def __init__(self, speaker_id=212):
    self.silence = 100000
    self.seg = "" # 分隔符
    self.size = 1 # 接口一次处理的行数
    self.token = getToken()
    self.url = "https://nls-gateway-cn-beijing.aliyuncs.com/stream/v1/tts?appkey=wtQoYnzGm3LkeGdo&token="+self.token+"&text=%s&format=wav&sample_rate=16000&speech_rate=%s"
    if speaker_id != 212:
      self.url = "https://nls-gateway-cn-beijing.aliyuncs.com/stream/v1/tts?appkey=qZeq5ZcloxaE4MjZ&token="+self.token+"&text=%s&format=wav&sample_rate=16000&speech_rate=%s"
    self.headers = {
            'Content-Type': 'application/json',
            # 'Authorization': 'Bearer lvZWS6o4GgABleInPH96x0RKKjYHZCCGXNJxx3m4YDz2VDvefVWaKMr/jE8VD3LiwEANBvBhNonCWFnhmoLTE8rFmYfahR88Z6/co6MImVY/kbn9oRHgHAe5HiPN2M9oV3u/L1w3RpRUZzsBe75Q7zRb5jHQyKAvtIm42zZJH0r9oTIXLxeTNMSkNRjuzr53bof4ddDLg/NAAqEgKT7AEtWoQEHfQPIBksih8ApdgBgk5qMm4zUfDQGMmj0/kda6x0LzQMIjWskBmK7v52FtXbmSxUvGdFB1DJXhnAGXt9iYtFyCLRLIYje0229hxKI/zU1ih5moTAoq9rOK3sfjFLTKuFnZNsgvGHO8I8dnmkxeWOWGCvDpS3Im3ZeBoVzfMpPNDRSPBvwzXhmJbdeG+apW+6CS0wXDnDt5GW6wWdEv1rmpixhz6e3gZTDK/M0M',
            }
    self.payload = {"ssml":"","speaker_id":speaker_id,"speaking_rate":1,"volume":1.06,"features_id":0,"effect_audios":[]}

  def readtofile(self, text, fn, speaking_rate=100):
    words = ["（笑声）","（掌声）","&gt;","&lt;","讲师：","\\N","（隆隆声）"]
    for word in words:
      text = text.replace(word, " ")
    r = requests.get(self.url % (text, speaking_rate))

    with open(fn,"wb") as code:
      code.write(r.content)

if __name__ == "__main__":
  r = Reader(212)
  r.readtofile("你好","../../tmp/1.mp3")
